package com.berchina.controller.admin;

import com.berchina.bean.Order;
import com.berchina.service.CustomerService;
import com.berchina.service.OrderService;
import com.berchina.util.JsonData;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private CustomerService customerService;
    @RequestMapping("/selectList")
    public String toOrderList(){
        return "/html/orders/table.html";
    }
    @RequestMapping("/getOrders")
    @ResponseBody
    public Object getOrders(String phone, String status,
                            @RequestParam(value = "page",defaultValue = "1") Integer page,
                            @RequestParam(value = "limit",defaultValue = "5") Integer limit){
        Map<String,Object> map=new HashMap<String, Object>();
        if(StringUtils.isEmpty(phone)){
            map.put("phone",phone);
        }
        if(StringUtils.isEmpty(status)){
            map.put("status",status);
        }
        PageInfo<Order> pageInfo=orderService.findByPages(map,page,limit);
        return JsonData.buildSuc(pageInfo);
    }
    @RequestMapping("add")
    public String add(){
        return "/html/orders/addOrder.html";
    }

    @RequestMapping("addOrder")
    @ResponseBody
    public Object addOrder(Order order,String name,String car){
        List<Order> orders=orderService.findByPhone(order.getPhone());
        if(orders==null||orders.size()==0){
            int x=customerService.saveCustomer(order.getPhone(),name,order.getAddress(),new Date(),car);
            int y = orderService.addOrder(order);
            if(x>0&&y>0){
                return "success";
            }

        }else{
            for(Order o:orders){
                if(o.getStatus().equals("3")){
                    int x=customerService.saveCustomer(order.getPhone(),name,order.getAddress(),new Date(),car);
                    int y = orderService.addOrder(order);
                    if(x>0&&y>0){
                        return "success";
                    }
                }
            }
        }
        return "error";
    }




    @RequestMapping("/sendMaster")
    public String sendMaster(){
        return "/html/orders/master/table.html";
    }
}
